package com.hnl.core;

import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.hnl.core.connection.HNLDBConnectionManager;

public class HNLDBInitializer {
	public static final Logger LOG = LoggerFactory
			.getLogger(HNLDBInitializer.class);

	public static void initDB() {
		NodeList elems = HNLCore.getHNLConfig().getDoc()
				.getElementsByTagName(HNLConfig.CONFIG);

		try {
			DataConfig dbConfig = new DataConfig();
			dbConfig.readDataSourcesFromXml((Element) elems.item(0));

			for (Map.Entry<String, Properties> entry : dbConfig.dataSources
					.entrySet()) {
				Properties prop = entry.getValue();
				String driverClassName = prop.getProperty("driver");
				HNLDBConnectionManager.getInstance().loadDrivers(
						driverClassName);
			}

			for (Map.Entry<String, Properties> entry : dbConfig.dataSources
					.entrySet()) {
				Properties prop = entry.getValue();
				String name = prop.getProperty("name");
				String url = prop.getProperty("url");
				String user = prop.getProperty("user");
				String password = prop.getProperty("password");
				int maxConn = HNLDBConnectionManager.DEFAULT_MAX_CONNECTION;
				if (prop.getProperty("pool") != null) {
					maxConn = Integer
							.valueOf((String) prop.getProperty("pool"));
				}
				HNLDBConnectionManager.getInstance().createPool(name, url,
						user, password, maxConn);
			}
		} catch (Exception e) {
			LOG.error("DB initialization failed", e);
		}
	}

}
